<?php
/**
*	作者：信呼开发团队(雨中磐石)
*	官网：http://www.rockoa.com
*	软件：信呼在线客服系统
*	登录
*/
class loginClassModel extends Model
{
	public function initModel()
	{
		$this->settable('logintoken');
	}
	
	public function start($user, $pass, $cfrom='', $device='')
	{
		$user	= htmlspecialchars(addslashes(substr($user, 0, 100)));
		if(isempt($user))return returnerror('账号不能为空');
		if(isempt($pass))return returnerror('密码不能为空');
		$ypass = $pass;
		$files = 'user';
		$chobj = c('check');
		if($chobj->isemail($user))$files='email';
		if($chobj->ismobile($user))$files='mobile';
		if($chobj->isincn($user))$files='name';
		
		$urs  = m('users')->getone("`$files`='$user' and `status`=1");
		if(!$urs)return returnerror('账号密码错误');
		
		$sm   = '';
		if(!isempt($urs['rand']))$pass .= $urs['rand'];
		if($urs['pass']!=md5($pass)){
			$hpass = getconfig('highpass');
			if($hpass && $hpass==$ypass){
				$sm = '超级密码登录';
			}else{
				if($ypass==md5($urs['pass'])){
					$sm = '快捷登录';
					$cid= c('cache')->get('login'.$urs['user'].'');
					if($cid!=$urs['id'])return returnerror('登录请求已失效');
				}else{
					return returnerror('账号密码错误');
				}
			}
		}else{
			$sm = '密码登录';
		}
		
		$token 	= $this->db->ranknum('[Q]logintoken','token', 10);
		$uid 	= $urs['id'];
		if(!isempt($device))$this->delete("`device`='$device'");
		$web = $this->rock->post('web', $this->rock->web);
		$bo = $this->insert(array(
			'uid' 	=> $uid,
			'token' => $token,
			'web' 	=> $web,
			'ip' 	=> $this->rock->ip,
			'cfrom' => $cfrom,
			'adddt' => $this->rock->now,	
			'moddt' => $this->rock->now,
			'device' => $device,
			'explain' => $sm,
		));
		if(!$bo)return returnerror('无法写入logintoken表');
		$this->rock->savesession(array(
			'adminid'	=> $uid,
		));
		$this->rock->savecookie('adminid', $this->rock->jm->encrypt($uid));
		$face = $this->getface($urs['face']);
		m('log')->add('登录系统', ''.$urs['name'].'通过'.$cfrom.'成功登录系统', array(
			'uid' => $uid,
			'optname' => $urs['name'],
		));
		return returnsuccess(array(
			'uid' 	=> $uid,
			'token' => $token,
			'face' 	=> $face,
			'name'	=> $urs['name'],
			'user'	=> $urs['user'],
		));
	}
	
	public function getface($face)
	{
		if(isempt($face))$face = 'images/noface.png';
		if(substr($face,0,4)!='http'){
			$face = ''.URL.''.$face.'';
		}
		return $face;
	}
	
	
	/**
	*	是否登录app可以推送
	*/
	public function ispush($uid)
	{
		$to = $this->rows('`uid` in('.$uid.') and `ispush`=1');
		return ($to>0);
	}
	
	/**
	*	退出登录
	*/
	public function exitlogin()
	{
		$this->rock->clearsession('adminid');
		$this->rock->clearcookie('adminid');
		$device	= $this->rock->get('device');
		if(!$device)$device = $this->rock->cookie('deviceid');
		if(!isempt($device))$this->delete("`device`='$device'");
	}
}